package com.kamloo.stg.utils;

import java.util.Random;
import com.kamloo.stg.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AnimatedView extends ImageView{

	public class Ball{
		int x = -1;
		int y = -1;
	}
	
	private Context mContext;
	int x = -1;
	int y = -1;
	private Handler h;
	private final int FRAME_RATE = 30;
	
	private Ball[] m_balls;
	private int[] m_xVelocity;
	private int[] m_yVelocity;
	
	private int m_nbBalls = 15;
	private Random m_random = new Random();
	
	
	
	public AnimatedView(Context context, AttributeSet attrs)  {  
		super(context, attrs);  
		mContext = context;  
		h = new Handler();
		m_balls = new Ball[m_nbBalls];
		m_xVelocity = new int[m_nbBalls];
		m_yVelocity = new int[m_nbBalls];
		
		for (int i = 0; i < m_nbBalls; i++) {
			m_balls[i] = new Ball() {{x = -1; y=-1;}}; 
			m_xVelocity[i] = m_random.nextInt(20);
			m_yVelocity[i] = m_random.nextInt(10);
		}
    } 
	
	private Runnable r = new Runnable() {
		public void run() {
			invalidate(); 
		}
	};
	
	protected void onDraw(Canvas c) {  
		
		BitmapDrawable ball = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.launcher);
		
		for (int i = 0; i < m_nbBalls; i++)
		{
			if (m_balls[i].x < 0 && m_balls[i].y <0) {
				m_balls[i].x = 0;
				m_balls[i].y = 0;
		    } else {
		    	m_balls[i].x += m_xVelocity[i];
		    	m_balls[i].y += m_yVelocity[i];
		    	if ((m_balls[i].x > this.getWidth() - ball.getBitmap().getWidth()) || (m_balls[i].x < 0)) {
		    		m_xVelocity[i] = m_xVelocity[i]*-1;
		    	}
		    	if ((m_balls[i].y > this.getHeight() - ball.getBitmap().getHeight()) || (m_balls[i].y < 0)) {
		    		m_yVelocity[i] = m_yVelocity[i]*-1;
		    	}
		    }
		    c.drawBitmap(ball.getBitmap(), m_balls[i].x, m_balls[i].y, null);
		}  
	    
	    h.postDelayed(r, FRAME_RATE);      
	} 
}
